package com.ysx.user.controller;

import com.alibaba.fastjson.JSON;
import com.ysx.user.service.UserService;
import com.ysx.user.service.impl.UserServiceImpl;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name="UserController",urlPatterns="/user/login.do")
public class UserController extends GenericServlet {
    
    private UserService userService= new UserServiceImpl();


    @Override
    public void service(ServletRequest servletRequest, ServletResponse response) throws ServletException, IOException {

        // 专门处理http协议的请求
        HttpServletRequest request= (HttpServletRequest)servletRequest;

        // 1 拿页面提交过来的数据
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");

        // 2 调用Service并拿到结果
        Integer rs = userService.login(phone, password);

        // 3 给页面反馈
        Map<String,Object> map = new HashMap<>();

        HttpSession session=request.getSession(true);
        if(rs!=null){

            // ServletRequest  request   代表 可以代表任何请求   代表处理http协议的请求
            // ServletResponse response 代表 响应

            // 在项目组  getSession中的必须写true 强制开启session
            session = request.getSession(true);

            //如果登陆成功 就把 userId=10010 放到1个很大的杯子中 方便别的Controller可以从session这个杯子中取
            session.setAttribute("userId",rs);

            map.put("code",200);
            map.put("message","success");
        }else{
            map.put("code",500);
            map.put("message","failure");
        }

        String jsonString =  JSON.toJSONString(map);


        PrintWriter writer = response.getWriter();
        writer.print(jsonString);
        writer.flush();
    }
}
